package main

import (
	"github.com/gin-gonic/gin"
	"ju/src/single"
	"ju/src/middleway"
	"net/http"
	"os"
	"os/signal"
	"time"
	"log"
	"context"
	"ju/src/handle/admin"
	"ju/src/handle"
	"ju/src/handle/normal"
)

var DB = make(map[string]string)
var router *gin.Engine

func checkErr(err error) {
	if err != nil {
		panic(err)
	}
}

func init() {
	router = single.GetRouter()

	router.Use(middleway.AuthRequired())
	router.Use(middleway.CORSMiddleware())
}

func main() {
	router.GET("/index", admin.Root)
	router.GET("/", admin.Root)

	authorized := router.Group("/admin")
	authorized.Use()
	{
		authorized.GET("/index", admin.Dashboard)
		authorized.POST("/login", admin.Login)
		authorized.GET("/register", admin.Register)
		authorized.POST("/forgetPwd", admin.ForgetPwd)
	}

	userHandles := router.Group("/normal")
	userHandles.Use()
	{
		userHandles.POST("/login", normal.Login)
		userHandles.GET("/register", normal.Register)
		userHandles.POST("/forgetPwd", normal.ForgetPwd)

		userHandles.GET("/getBillDetail", normal.GetBill)
		userHandles.GET("/payBill", normal.PayBill)
		userHandles.POST("/part1Info", normal.Part1Info)
		userHandles.POST("/part2Info", normal.Part2Info)
		userHandles.GET("/getBillList", normal.GetUserBill)
	}

	router.POST("/upload", handle.Upload)

	start()
}

/**
 开始函数
 */
func start() {
	srv := &http.Server{
		Addr:    ":9090",
		Handler: router,
	}
	go func() {
		// service connections
		if err := srv.ListenAndServe(); err != nil {
			log.Printf("listen: %s\n", err)
		}
	}()
	quit := make(chan os.Signal)
	signal.Notify(quit, os.Interrupt)
	<-quit
	log.Println("Shutdown Server ...")

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	if err := srv.Shutdown(ctx); err != nil {
		log.Fatal("Server Shutdown:", err)
	}
	log.Println("Server exist")
}
